package ren.kane.phoenix.util.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * @author renrk(1275) on 2019-07-31 3:01 PM
 **/
public class FileStreamTest {

    private static final String FILE_NAME = "file.txt";

    public static void main(String[] args) {
        testWrite();
        testRead();
    }

    /**
     * 在源码所在目录生成文件"file.txt"，文件内容是“abcdefghijklmnopqrstuvwxyz0123456789”
     */
    private static void testWrite() {
        try {
            File file = new File("dir", FILE_NAME);
            FileOutputStream fileOutputStream1 = new FileOutputStream(file);
            PrintStream printStream1 = new PrintStream(fileOutputStream1);
            printStream1.print("abcdefghijklmnopqrstuvwxyz");
            printStream1.close();
            // 创建文件“file.txt”对应的FileOutputStream对象，打开“追加模式”
            FileOutputStream fileOutputStream2 = new FileOutputStream(file, true);
            PrintStream printStream2 = new PrintStream(fileOutputStream2);
            printStream2.print("0123456789");
            printStream2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void testRead() {
        try {
            File file = new File(FILE_NAME);
            FileInputStream fileInputStream1 = new FileInputStream(file);
            FileInputStream fileInputStream2 = new FileInputStream(FILE_NAME);
            FileDescriptor fileDescriptor = fileInputStream2.getFD();
            FileInputStream fileInputStream3 = new FileInputStream(fileDescriptor);

            char c1 = (char) fileInputStream1.read();
            System.out.println("c1=" + c1);
            fileInputStream1.skip(25);

            byte[] buf = new byte[10];
            fileInputStream1.read(buf, 0, buf.length);
            System.out.println("buf=" + (new String(buf)));

            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream3);
            char c2 = (char) bufferedInputStream.read();
            System.out.println("c2=" + c2);

            fileInputStream1.close();
            fileInputStream2.close();
            fileInputStream3.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
